package com.mega.fe.util.transformer;

import com.mega.fe.asm.*;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.reflect.Modifier;
import java.security.ProtectionDomain;

public class CommonClassFileTransformer implements ClassFileTransformer {
    @Override
    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
        return ClassFileTransformer.super.transform(loader, className, classBeingRedefined, protectionDomain, classfileBuffer);
    }

    public static byte[] transformGLFW() throws Throwable{
        ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
        ClassReader classReader = new ClassReader("org/lwjgl/glfw/GLFW");
        ClassVisitor classVisitor = new ClassVisitor(Opcodes.ASM7, classWriter) {
            @Override
            public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
                if (name.equals("glfwSetWindowTitle") && descriptor.equals("(JLjava/lang/CharSequence;)V")) {
                    return null;
                }

                return super.visitMethod(access, name, descriptor, signature, exceptions);

            }

            @Override
            public void visitEnd() {
                MethodVisitor mv = cv.visitMethod(Modifier.PUBLIC | Modifier.STATIC, "glfwSetWindowTitle", "(JLjava/lang/CharSequence;)V", null, null);
                mv.visitCode();
                mv.visitMethodInsn(Opcodes.INVOKESTATIC
                        , "com/mega/fe/util/klass/EventUtil"
                        , "glfwSetWindowTitle"
                        , "()V"
                        ,false);
                mv.visitInsn(Opcodes.RETURN);
                mv.visitMaxs(3, 3);
                super.visitEnd();
            }
        };
        classReader.accept(classVisitor, 0);

        return classWriter.toByteArray();
    }
}
